"""
Redis配置类
用于管理Redis连接配置
"""

import os
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()


class RedisConfig:
    """Redis配置类"""
    
    # Redis连接配置
    REDIS_HOST = os.getenv('REDIS_HOST', 'localhost')
    REDIS_PORT = int(os.getenv('REDIS_PORT', 6379))
    REDIS_PASSWORD = os.getenv('REDIS_PASSWORD', None)
    REDIS_DB = int(os.getenv('REDIS_DB', 7))
    
    # Redis连接池配置
    REDIS_CONNECTION_POOL_MAX_CONNECTIONS = int(os.getenv('REDIS_CONNECTION_POOL_MAX_CONNECTIONS', 50))
    REDIS_CONNECTION_POOL_RETRY_ON_TIMEOUT = os.getenv('REDIS_CONNECTION_POOL_RETRY_ON_TIMEOUT', 'true').lower() == 'true'
    
    # Redis超时配置
    REDIS_SOCKET_TIMEOUT = int(os.getenv('REDIS_SOCKET_TIMEOUT', 5))
    REDIS_SOCKET_CONNECT_TIMEOUT = int(os.getenv('REDIS_SOCKET_CONNECT_TIMEOUT', 5))
    
    # 缓存过期时间配置（秒）
    CACHE_DEFAULT_TIMEOUT = int(os.getenv('CACHE_DEFAULT_TIMEOUT', 300))  # 5分钟
    CACHE_LONG_TIMEOUT = int(os.getenv('CACHE_LONG_TIMEOUT', 3600))  # 1小时
    CACHE_SHORT_TIMEOUT = int(os.getenv('CACHE_SHORT_TIMEOUT', 60))  # 1分钟
    
    # 会话过期时间配置（秒）
    SESSION_TIMEOUT = int(os.getenv('SESSION_TIMEOUT', 86400))  # 24小时
    
    @classmethod
    def get_redis_url(cls):
        """获取Redis连接URL"""
        if cls.REDIS_PASSWORD:
            return f"redis://:{cls.REDIS_PASSWORD}@{cls.REDIS_HOST}:{cls.REDIS_PORT}/{cls.REDIS_DB}"
        return f"redis://{cls.REDIS_HOST}:{cls.REDIS_PORT}/{cls.REDIS_DB}"
    
    @classmethod
    def get_redis_config(cls):
        """获取Redis连接配置字典"""
        config = {
            'host': cls.REDIS_HOST,
            'port': cls.REDIS_PORT,
            'db': cls.REDIS_DB,
            'socket_timeout': cls.REDIS_SOCKET_TIMEOUT,
            'socket_connect_timeout': cls.REDIS_SOCKET_CONNECT_TIMEOUT,
            'max_connections': cls.REDIS_CONNECTION_POOL_MAX_CONNECTIONS,
            'retry_on_timeout': cls.REDIS_CONNECTION_POOL_RETRY_ON_TIMEOUT,
        }
        
        if cls.REDIS_PASSWORD:
            config['password'] = cls.REDIS_PASSWORD
            
        return config